package org.example.mywebsite.config;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    public Interceptor interceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("添加拦截器");
        registry.addInterceptor(interceptor)
                .addPathPatterns("/admin/**")
                .addPathPatterns("/music/upload");
    }

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许前端域名（替换为你的前端实际地址，如 http://localhost:5174）
        config.addAllowedOrigin("http://localhost:5174");
        // 允许携带凭证（如Cookie、Token）
        config.setAllowCredentials(true);
        // 允许所有请求方法（GET、POST、OPTIONS等）
        config.addAllowedMethod("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许前端访问的响应头（可选，按需添加）
        config.addExposedHeader("Authorization");
        // 预检请求缓存时间（减少重复预检请求，单位：秒）
        config.setMaxAge(3600L);

        // 配置跨域路径（所有接口都允许跨域）
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}